<!doctype html>
<html class="theme-next   use-motion ">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/>




  
    <link href='//fonts.lug.ustc.edu.cn/css?family=Lato:300,400,700,400italic&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
  



<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=0.4.5.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android,BaseAdapter," />





  <link rel="alternate" href="/atom.xml" title="黎稀" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=0.4.5.2" />






<meta name="description" content="最后编辑时间：2015-11-20 15:36自从看了鸿神的打造 万能适配器 之后，就一直有想根据自己项目需求修改一个版本。于是我的 CommonAdapter 1.0 就这样诞生了,虽然后面有更新代码，但是觉得并不符合Common的理念，于是就没有将2.0更新到GitHub上。而3.0的回炉重造，也是这个时候起了念头。嗯哼，终于在偷懒了无数个日头后，开始将 操 码了出来。

简介CommonAd">
<meta property="og:type" content="article">
<meta property="og:title" content="回炉重造的BaseAdapter3.0">
<meta property="og:url" content="http://lixicode.com/android/android-adapter/index.html">
<meta property="og:site_name" content="黎稀">
<meta property="og:description" content="最后编辑时间：2015-11-20 15:36自从看了鸿神的打造 万能适配器 之后，就一直有想根据自己项目需求修改一个版本。于是我的 CommonAdapter 1.0 就这样诞生了,虽然后面有更新代码，但是觉得并不符合Common的理念，于是就没有将2.0更新到GitHub上。而3.0的回炉重造，也是这个时候起了念头。嗯哼，终于在偷懒了无数个日头后，开始将 操 码了出来。

简介CommonAd">
<meta property="og:image" content="http://lixicode.com/uml_common_adapter3.0.jpg">
<meta property="og:updated_time" content="2015-11-20T08:23:37.555Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="回炉重造的BaseAdapter3.0">
<meta name="twitter:description" content="最后编辑时间：2015-11-20 15:36自从看了鸿神的打造 万能适配器 之后，就一直有想根据自己项目需求修改一个版本。于是我的 CommonAdapter 1.0 就这样诞生了,虽然后面有更新代码，但是觉得并不符合Common的理念，于是就没有将2.0更新到GitHub上。而3.0的回炉重造，也是这个时候起了念头。嗯哼，终于在偷懒了无数个日头后，开始将 操 码了出来。

简介CommonAd">



<script type="text/javascript" id="hexo.configuration">
  var CONFIG = {
    scheme: 'Mist',
    sidebar: 'post',
    motion: true
  };
</script>

  <title> 回炉重造的BaseAdapter3.0 | 黎稀 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  <!--[if lte IE 8]>
  <div style=' clear: both; height: 59px; padding:0 0 0 15px; position: relative;margin:0 auto;'>
    <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
      <img src="http://7u2nvr.com1.z0.glb.clouddn.com/picouterie.jpg" border="0" height="42" width="820"
           alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today or use other browser ,like chrome firefox safari."
           style='margin-left:auto;margin-right:auto;display: block;'/>
    </a>
  </div>
<![endif]-->
  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?c76cdc9b7b93baaf7d2ada3220916af8";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div class="container one-column page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">黎稀</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-home fa-fw"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-archive fa-fw"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-tags fa-fw"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-user fa-fw"></i> <br />
            
            关于
          </a>
        </li>
      

      
      
    </ul>
  

  
    <div class="site-search">
      
  
  <form class="site-search-form">
    <input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
  </form>


<script type="text/javascript">
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
    (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
    e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
  })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');

  _st('install', 'h_1LpcE4jz_K3ErpxpDg','2.0.0');
</script>



    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div id="content" class="content">
          

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                回炉重造的BaseAdapter3.0
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            发表于
            <time itemprop="dateCreated" datetime="2015-11-09T16:00:02+08:00" content="2015-11-09">
              2015-11-09
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
              &nbsp; | &nbsp;
              <a href="/android/android-adapter/#comments" itemprop="discussionUrl">
                <span class="post-comments-count disqus-comment-count" data-disqus-identifier="android/android-adapter/" itemprop="commentsCount"></span>
              </a>
            </span>
            
          

          

        </div>
      </header>
    


    <div class="post-body">

      
      

      
        <span itemprop="articleBody"><blockquote>
<p>最后编辑时间：2015-11-20 15:36<br>自从看了鸿神的打造 <a href="http://www.imooc.com/view/372" target="_blank" rel="external">万能适配器</a> 之后，就一直有想根据自己项目需求修改一个版本。于是我的 <a href="https://github.com/lixi0912/Common-BaseAdapter-And-ViewHolder" target="_blank" rel="external">CommonAdapter 1.0</a> 就这样诞生了,虽然后面有更新代码，但是觉得并不符合Common的理念，于是就没有将2.0更新到GitHub上。而3.0的回炉重造，也是这个时候起了念头。嗯哼，终于在偷懒了无数个日头后，开始将 <del>操</del> 码了出来。</p>
</blockquote>
<h1 id="简介">简介</h1><p>CommonAdapter是一个抽简BaseAdapter重复代码为主要目的的Lib。</p>
<ol>
<li>抽离通用逻辑块</li>
<li>findViewById模式，并通过SparseArray缓存使用的View。可以在此基础上定义一些常用的View操作方法。这个模式也是在鸿洋这边看到的，不过在使用过程中发现，在不同的子项中会有不同的引用框架，并不通用。所以在此我并没有像之前把这些常用操作方法集成进来。希望在子项目中有自己的AutoCacheHolder。</li>
<li>RecycleView.ViewHolder模式，通过成员变量缓存View</li>
<li>通过缓存可见Holder（不包含重用的Holder），以及匹配Holder中的Tag，来对view进行刷新操作<blockquote>
<p>优点：</p>
<ul>
<li>可以简化Adapter的代码，将原本数百行的代码，简洁到数十行。（实际代码量并没有减少）</li>
</ul>
</blockquote>
</li>
</ol>
<p>如果你爱偷懒，那么很适合你，如果你已经换成了RecycleView，嗯，你可以跳过一大部分了~</p>
<h2 id="对万能适配器的拓展">对<a href="http://www.imooc.com/view/372" target="_blank" rel="external">万能适配器</a>的拓展</h2><ul>
<li>支持单个item刷新</li>
<li>内部提供对list操作管理</li>
</ul>
<h2 id="实际考虑">实际考虑</h2><ul>
<li>抽离通用代码块</li>
<li>数据增加，删除，获取</li>
<li>单个item的刷新</li>
<li>兼容自定义View和layout布局</li>
<li>一些关键操作检测是否在UI线程</li>
<li>嗯，参考RecycleView.ViewHolder的定义</li>
</ul>
<p>由于之前的CommAdapter 1.x 和未上传的CommonAdapter 2.x（耦合都比较大，2系列实在不好意思提交代码了，不过这边会放出ExpandableListAdapter的拓展）都是写完了之后，因为项目的需求进行缝缝补补。感觉并不是很好，so，这个版本希望先设计好再进行更新。</p>
<h1 id="变更历史">变更历史</h1><blockquote>
<h2 id="1-0">1.0</h2><ul>
<li>通过泛型，抽出List（并支持外部指定），并在Adapter中提供Add，Remove等常用操作</li>
<li>通过Holder，对单个item进行刷新</li>
<li>缺点：仅能和Adapter搭配使用</li>
</ul>
<h2 id="2-0">2.0</h2><ul>
<li>提供ExpandListAdapter的支持</li>
</ul>
<h2 id="3-0">3.0</h2><ul>
<li>解耦合，尝试BindView形式</li>
<li>放弃一些常用的方法setText,loadImage,因为觉得这些方法，应该是在指定的Holder中去指配</li>
</ul>
</blockquote>
<h1 id="陷阱">陷阱</h1><blockquote>
<h2 id="此处该有高能陷阱">此处该有高能陷阱</h2><ul>
<li>对于相同id，不同实例的数据集会出现更新错乱</li>
<li>对于相同id，相同实例的数据集只会更新一个，而重用后出现所有的数据更新<blockquote>
<p>解决方式： 乖乖的使用notifyDataSetChange();</p>
</blockquote>
</li>
</ul>
</blockquote>
<h1 id="快看类图">快看类图</h1><blockquote>
<p>不怎么会用uml，如果有什么错误烦请指出，不胜感激。</p>
</blockquote>
<p><img src="http://lixicode.com/uml_common_adapter3.0.jpg" alt=""></p>
<ol>
<li>IDataProxy<br>数据集的代理类，意为通过该代理，简单快速的对数据集进行操作,其包含了他的干粗活的儿子DataProxyImpl，还有他不争气的儿子的私生子UIDataProxy（额，之所以说是私生的，是因为其内部持有一个我觉得没必要的Handler。在对添加的方法判断其线程所在的是否是主线程，如果不是就将其抛到子线程。然而在移除的时候，就需要在外部调用，与最初的设计理念有点相悖。想想，还是先保留着。欢迎指点迷津~）</li>
<li>BaseAdapterEx<br>嗯，IDataProxy的同胞兄弟。而其孙子AutoCacheHolderAdapter则有一些使用的限制，需要重写实体类的equles方法和hashCode。</li>
<li>IHolder<br>用来处理View的显示~在与BaseHolderAdapter搭配使用的是其子类IListHolder,而我更喜欢的是已经有初步的定义方法的HolderImpl。</li>
</ol>
<h1 id="使用">使用</h1><p>在此贴出一些伪代码</p>
<h2 id="以下是鸡肋">以下是鸡肋</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Menu</span> </span>&#123;</span><br><span class="line">	<span class="comment">/** 标识符 */</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">final</span> String id;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//AndSomeCode</span></span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">hashCode</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> id.hashCode();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="annotation">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">equals</span><span class="params">(Object o)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">null</span> == o) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">super</span>.equals(o)) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (id.equals(o)) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">this</span>.getClass() == o.getClass()) &#123;</span><br><span class="line">			<span class="keyword">return</span> id.equals(((Menu) o).id);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">	&#125;</span><br><span class="line">    <span class="comment">//AndSomeCode</span></span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Viewholder三种攻防">Viewholder三种攻防</h2><ul>
<li><p>自定义BindView 伪代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BindView</span> <span class="keyword">extends</span> <span class="title">TextView</span> <span class="title">implents</span> <span class="title">IHolder</span>&lt;<span class="title">Menu</span>&gt;</span>&#123;</span><br><span class="line">    <span class="comment">//AndSomeCode</span></span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">	<span class="annotation">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onDataBinding</span><span class="params">(Menu data)</span> </span>&#123;</span><br><span class="line">		setText(data.getTitle());</span><br><span class="line">	&#125;</span><br><span class="line">    <span class="comment">//AndSomeCode</span></span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>类似RecycleView.ViewHolder</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleHolder</span> <span class="keyword">extends</span> <span class="title">IHolder</span>.<span class="title">HolderImpl</span>&lt;<span class="title">Menu</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">private</span> TextView mTitleTv;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="title">SimpleHolder</span><span class="params">(View content)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">super</span>(content);</span><br><span class="line">			<span class="keyword">this</span>.mTitleTv = (TextView) findViewById(R.id.tv_title);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="annotation">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onDataBinding</span><span class="params">(<span class="keyword">int</span> position, <span class="keyword">int</span> itemViewType, Menu data)</span> </span>&#123;</span><br><span class="line">			mTitleTv.setText(data.getTitle());</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>AutoCacheHolder</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleHolder</span> <span class="keyword">extends</span> <span class="title">IHolder</span>.<span class="title">HolderImpl</span>&lt;<span class="title">Menu</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="title">SimpleHolder</span><span class="params">(View content)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">super</span>(content);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="annotation">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onDataBinding</span><span class="params">(<span class="keyword">int</span> position, <span class="keyword">int</span> itemViewType, Menu data)</span> </span>&#123;</span><br><span class="line">			((TextView)findViewById(R.id.tv_title)).setText(data.getTitle());</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="交_叉搭_配">交 <del>叉搭</del> 配</h2><ul>
<li><p>复杂布局搭配使用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> AutoCacheHolderAdapter&lt;Menu&gt; adapter = <span class="keyword">new</span> AutoCacheHolderAdapter&lt;Menu&gt;(Menu.getUpdateList()) &#123;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">final</span> <span class="keyword">static</span> <span class="keyword">int</span> LAYOUT_SIMPLE = <span class="number">0</span>;</span><br><span class="line">		<span class="keyword">final</span> <span class="keyword">static</span> <span class="keyword">int</span> LAYOUT_MULTIPLE = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">		<span class="annotation">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getItemViewType</span><span class="params">(<span class="keyword">int</span> position)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">return</span> position &lt; <span class="number">2</span> ? LAYOUT_SIMPLE : LAYOUT_MULTIPLE;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="annotation">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getViewTypeCount</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="number">2</span>;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="annotation">@Override</span></span><br><span class="line">		<span class="keyword">protected</span> IHolder.<span class="function">IListHolder&lt;Menu&gt; <span class="title">createHolder</span><span class="params">(<span class="keyword">int</span> position, <span class="keyword">int</span> itemViewType, Menu data)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">if</span> (getItemViewType(position) == LAYOUT_SIMPLE) &#123;</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">new</span> SimpleHolder(inflate(R.layout.item_menu));</span><br><span class="line">			&#125; <span class="keyword">else</span> &#123;<span class="comment">// LAYOUT_MULTIPLE</span></span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">new</span> AutoCacheHolder&lt;Menu&gt;(inflate(R.layout.item_multiple)) &#123;</span><br><span class="line"></span><br><span class="line">					<span class="annotation">@Override</span></span><br><span class="line">				  	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onDataBinding</span><span class="params">(<span class="keyword">int</span> position, <span class="keyword">int</span> itemViewType, Menu data)</span> </span>&#123;</span><br><span class="line">						((TextView) findViewById(R.id.tv_title)).setText(data.getTitle());</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">	&#125;;</span><br><span class="line">	<span class="comment">// 当需要再Adapter中使用inflate时，需要添加布局解析器</span></span><br><span class="line">	adapter.inflater(getLayoutInflater());</span><br></pre></td></tr></table></figure>
</li>
<li><p>简单布局（对于只有单个View）<br>对于简单布局来说，我觉得没有必要使用ViewHolder，当然如果你想用更简洁的代码，也是口译的额，反正我也不会拦着你！</p>
<blockquote>
<p>而当你对Tag需要操作时，ViewHolder就不再适用了~</p>
</blockquote>
</li>
</ul>
<p>那么，该怎么定义简单布局的Adapter呢？<br>让我们来看一看伪代码~<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> BaseAdapterEx&lt;Menu&gt; mAdapter = <span class="keyword">new</span> BaseAdapterEx&lt;Menu&gt;(Menu.create()) &#123;</span><br><span class="line"></span><br><span class="line">	<span class="annotation">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> View <span class="title">getView</span><span class="params">(<span class="keyword">int</span> position, View convertView, ViewGroup parent)</span> </span>&#123;</span><br><span class="line">		TextView view = <span class="keyword">null</span>;</span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">null</span> == convertView) &#123;</span><br><span class="line">			view = <span class="keyword">new</span> TextView(parent.getContext());</span><br><span class="line">			view.setPadding(<span class="number">10</span>, <span class="number">10</span>, <span class="number">10</span>, <span class="number">10</span>);</span><br><span class="line">			view.setGravity(Gravity.CENTER);</span><br><span class="line">			convertView = view;</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			view = (TextView) convertView;</span><br><span class="line">		&#125;</span><br><span class="line">		view.setText(getItem(position).getTitle());</span><br><span class="line">		<span class="keyword">return</span> convertView;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>如果需要对数据操作，也只需要通过mAdapter调用IDataProxy的方法。是不是也很简洁舒爽呢~</p>
<h2 id="刷新">刷新</h2><p> 单个item刷新：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">AutoCacheHolderAdapter.reBindData(adapter.indexOf(Object));</span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>需要注意的：</p>
<ul>
<li>对于相同id，不同实例的数据集会出现更新错乱</li>
<li>对于相同id，相同实例的数据集只会更新一个，而重用后出现所有的数据更新<blockquote>
<p>解决方式： 乖乖的使用notifyDataSetChange();</p>
</blockquote>
</li>
<li>单个item仅有AutoCacheHolderAdapter提供使用~在BaseHolderAdapter，以及BaseHolderAdapter，BaseAdapterEx都没有提供相关的方法</li>
</ul>
</blockquote>
<p>其他刷新方式：（就是你啦）<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Adapter.notifyDataSetChange();</span><br></pre></td></tr></table></figure></p>
<h1 id="未来">未来</h1><p>嗯，RecycleView，欢迎你~<br>可以和IDataProxy，做一个RecycleView.ViewHolderEx</p>
<h1 id="感谢">感谢</h1><p><a href="http://blog.csdn.net/lmj623565791" target="_blank" rel="external">鸿洋 CSDN 传送门</a></p>
<h1 id="源码地址"><a href="https://github.com/lixi0912/CommonAdapter" target="_blank" rel="external">源码地址</a></h1><h4 id="版权声明：本文为博主原创文章，未经博主允许不得转载。">版权声明：本文为博主原创文章，未经博主允许不得转载。</h4></span>
      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag">#Android</a>
          
            <a href="/tags/BaseAdapter/" rel="tag">#BaseAdapter</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/android/android-studio/" rel="next" title="史丢丢笔记">
                <i class="fa fa-chevron-left"></i> 史丢丢笔记
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


        </div>

        


        
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
      </div>
    
  </div>


      </div>

      
        
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" src="http://tp2.sinaimg.cn/1806625505/180/40077142424/1" alt="黎稀" itemprop="image"/>
          <p class="site-author-name" itemprop="name">黎稀</p>
        </div>
        <p class="site-description motion-element" itemprop="description"></p>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">2</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          <div class="site-state-item site-state-categories">
            
              <span class="site-state-item-count">0</span>
              <span class="site-state-item-name">分类</span>
              
          </div>

          <div class="site-state-item site-state-tags">
            <a href="/tags">
              <span class="site-state-item-count">3</span>
              <span class="site-state-item-name">标签</span>
              </a>
          </div>

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/rainy0912" target="_blank">
                  
                    <i class="fa fa-weibo"></i> Weibo
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://github.com/lixi0912" target="_blank">
                  
                    <i class="fa fa-github"></i> GitHub
                  
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="http://creativecommons.org/licenses/by-sa/4.0" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator">
            <i class="fa fa-angle-double-up"></i>
          </div>
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#对万能适配器的拓展"><span class="nav-number">1.1.</span> <span class="nav-text">对万能适配器的拓展</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实际考虑"><span class="nav-number">1.2.</span> <span class="nav-text">实际考虑</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#变更历史"><span class="nav-number">2.</span> <span class="nav-text">变更历史</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-0"><span class="nav-number">2.1.</span> <span class="nav-text">1.0</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-0"><span class="nav-number">2.2.</span> <span class="nav-text">2.0</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-0"><span class="nav-number">2.3.</span> <span class="nav-text">3.0</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#陷阱"><span class="nav-number">3.</span> <span class="nav-text">陷阱</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#此处该有高能陷阱"><span class="nav-number">3.1.</span> <span class="nav-text">此处该有高能陷阱</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#快看类图"><span class="nav-number">4.</span> <span class="nav-text">快看类图</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用"><span class="nav-number">5.</span> <span class="nav-text">使用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#以下是鸡肋"><span class="nav-number">5.1.</span> <span class="nav-text">以下是鸡肋</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Viewholder三种攻防"><span class="nav-number">5.2.</span> <span class="nav-text">Viewholder三种攻防</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#交_叉搭_配"><span class="nav-number">5.3.</span> <span class="nav-text">交 叉搭 配</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#刷新"><span class="nav-number">5.4.</span> <span class="nav-text">刷新</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#未来"><span class="nav-number">6.</span> <span class="nav-text">未来</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#感谢"><span class="nav-number">7.</span> <span class="nav-text">感谢</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#源码地址"><span class="nav-number">8.</span> <span class="nav-text">源码地址</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#版权声明：本文为博主原创文章，未经博主允许不得转载。"><span class="nav-number">8.0.0.1.</span> <span class="nav-text">版权声明：本文为博主原创文章，未经博主允许不得转载。</span></a></li></ol></li></ol></li></ol></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator">
            <i class="fa fa-angle-double-down"></i>
          </div>
        </section>
      

    </div>
  </aside>


      
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2015</span>
  <span class="with-love">
    <i class="icon-next-heart fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">黎稀</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>



      </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  

  
    
    

  

    <script type="text/javascript">
      var disqus_shortname = 'lixicode';
      var disqus_identifier = 'android/android-adapter/';
      var disqus_title = '回炉重造的BaseAdapter3.0';
      var disqus_url = 'http://lixicode.com/android/android-adapter/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  


  

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>
  <script type="text/javascript" src="/js/fancy-box.js?v=0.4.5.2"></script>


  <script type="text/javascript" src="/js/helpers.js?v=0.4.5.2"></script>
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>
<script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

<script type="text/javascript" src="/js/motion.js?v=0.4.5.2" id="motion.global"></script>


  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  
<script type="text/javascript" src="/js/bootstrap.scrollspy.js?v=0.4.5.2" id="bootstrap.scrollspy.custom"></script>


<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 1 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    motionMiddleWares.sidebar = function () {
      var $tocContent = $('.post-toc-content');
      if (CONFIG.sidebar === 'post') {
        if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
          displaySidebar();
        }
      }
    };
  });
</script>



  <script type="text/javascript" src="/js/bootstrap.js"></script>

  
  
  <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
  </script>

  <script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for (i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  </script>

  
    <script type="text/javascript" src="http://cdn.staticfile.org/mathjax/2.4.0/MathJax.js"></script>
    <script type="text/javascript" src="http://cdn.staticfile.org/mathjax/2.4.0/config/TeX-AMS-MML_HTMLorMML.js"></script>
  


  
  

</body>
</html>
